package com.dd.edu.oss.controller;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class CryptoUtils {
	public static final String SHA1_ALGORITHM = "SHA-1";
	public static final String DEL_KEY_IPADDRESS = "ipaddress";
	public static final String DEL_KEY_CKVALUE = "ckvalue";


	/**
	 * SHA-1验签
	 *
	 * @param maps
	 * @param key：密钥
	 * @param serverSign：验签串
	 * @return
	 */
	public static boolean verifyObject(Map<String, Object> maps, String key, String serverSign) {
		String strSign = signObject(maps, key);
		if (strSign.equalsIgnoreCase(serverSign)) {
			return true;
		}
		return false;
	}


	/**
	 * SHA-1签名
	 *
	 * @param maps
	 * @param key
	 * @return
	 */
	public static String signObject(Map<String, Object> maps, String key) {
		//获取信息摘要 - 参数字典排序后字符串
		String decrypt = buildObjectSortWaitSign(maps, false);
		if (decrypt.lastIndexOf("&") == decrypt.length() - 1) {
			decrypt += "key=" + key;
		} else {
			decrypt += "&key=" + key;
		}
		//指定sha1算法

		StringBuilder sbErr = new StringBuilder();
		try {
			//获取字节数组
			byte[] messageDigest = sign(SHA1_ALGORITHM, decrypt, sbErr);
			return bytesToHexString(messageDigest);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}


	public static String buildObjectSortWaitSign(Map<String, Object> mapPars, boolean ExcludeBlankValue) {
		StringBuilder sbPars = new StringBuilder();
		List<String> lsPars = new ArrayList<String>();
		for (Iterator i = mapPars.keySet().iterator(); i.hasNext(); ) {
			String strKey = String.valueOf(i.next());
			lsPars.add(strKey);
		}
		String[] tmpPars = (String[]) lsPars.toArray(new String[lsPars.size()]);
		Arrays.sort(tmpPars);
		for (Integer i = 0; i < tmpPars.length; i++) {
			String strKey = tmpPars[i];
			// ipaddress 字段、ckvalue 字段 不参与签名
			if(strKey.equals(DEL_KEY_IPADDRESS) || strKey.equals(DEL_KEY_CKVALUE)){
				continue;
			}

			String strValue = String.valueOf(mapPars.get(strKey));
			if (null == strValue || strValue.length() == 0) {
				if (ExcludeBlankValue) {
					strValue = "";
				} else {
					continue;
				}
			}
			if (i == tmpPars.length - 1) {
				sbPars.append(String.format("%s=%s", strKey, strValue));
			} else {
				sbPars.append(String.format("%s=%s&", strKey, strValue));
			}
		}
		return sbPars.toString();
	}


	public static byte[] sign(String algorithm, String waitSign, StringBuilder sbErr) {
		MessageDigest digest;
		try {
			digest = MessageDigest.getInstance(SHA1_ALGORITHM);
			digest.update(waitSign.getBytes("UTF-8"));
			//获取字节数组
			return digest.digest();
		} catch (NoSuchAlgorithmException e) {
			sbErr.append(String.format("发生异常：%s", e));
			e.printStackTrace();
		} catch (Exception ex) {
			sbErr.append(String.format("异常：%s", ex));
		}
		return null;
	}

	/**
	 * 将字节转成十六进制字符串
	 *
	 * @param p_bytes
	 * @return
	 */
	public static String bytesToHexString(byte[] p_bytes) {
		if (p_bytes == null || p_bytes.length <= 0) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < p_bytes.length; i++) {
			int each = p_bytes[i] & 0xFF;
			String eachHex = Integer.toHexString(each);
			if (eachHex.length() < 2) {
				sb.append(0);
			}
			sb.append(eachHex);
		}
		return sb.toString();
	}

}
